﻿namespace PlugNT.Common
{
    using Microsoft.JScript;
    using Microsoft.VisualBasic;
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Drawing;
    using System.Globalization;
    using System.IO;
    using System.Net;
    using System.Reflection;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.UI;
    using System.Xml.Serialization;

    public abstract class Utils
    {
        private static FileVersionInfo AssemblyFileVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);
        private static CultureInfo CultureInfoDate = CultureInfo.CreateSpecificCulture("en-US");
        private static DateTime UnixStartTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(0x7b2, 1, 1));

        protected Utils()
        {
        }

        public static bool BackupFile(string sourceFileName, string destFileName)
        {
            return BackupFile(sourceFileName, destFileName, true);
        }

        public static bool BackupFile(string sourceFileName, string destFileName, bool overwrite)
        {
            if (!System.IO.File.Exists(sourceFileName))
            {
                throw new FileNotFoundException(sourceFileName + "文件不存在！");
            }
            if (!overwrite && System.IO.File.Exists(destFileName))
            {
                return false;
            }
            try
            {
                System.IO.File.Copy(sourceFileName, destFileName, true);
                return true;
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public static bool CheckColorValue(string color)
        {
            if (IsNullOrEmpty(color))
            {
                return false;
            }
            color = color.Trim().Trim(new char[] { '#' });
            if ((color.Length != 3) && (color.Length != 6))
            {
                return false;
            }
            return !Regex.IsMatch(color, "[^0-9a-f]", RegexOptions.IgnoreCase);
        }

        public static string ClearInput(string strIn)
        {
            return Regex.Replace(strIn.Trim(), @"[^\w\.@-]", "");
        }

        public static string ClearLastChar(string str)
        {
            if (str == "")
            {
                return "";
            }
            return str.Substring(0, str.Length - 1);
        }

        public static string ClearSpace(string strIn)
        {
            return Regex.Replace(strIn, @"\s+", "");
        }

        public static long ConvertDateTime(System.DateTime time)
        {
            return (long)(time - UnixStartTime).TotalSeconds;
        }

        public static bool CreateDir(string name)
        {
            return MakeSureDirectoryPathExists(name);
        }

        public static bool CreateFile(string filePath, string text)
        {
            return CreateFile(filePath, text, Encoding.Default);
        }

        public static bool CreateFile(string filePath, string text, Encoding tmpEncoding)
        {
            try
            {
                StreamWriter sw = new StreamWriter(filePath, false, tmpEncoding);
                sw.WriteLine(text);
                sw.Flush();
                sw.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static string CutString(string str, int startIndex)
        {
            return CutString(str, startIndex, str.Length);
        }

        public static string CutString(string str, int startIndex, int length)
        {
            if (startIndex >= 0)
            {
                if (length < 0)
                {
                    length *= -1;
                    if ((startIndex - length) < 0)
                    {
                        length = startIndex;
                        startIndex = 0;
                    }
                    else
                    {
                        startIndex -= length;
                    }
                }
                if (startIndex > str.Length)
                {
                    return "";
                }
            }
            else if ((length >= 0) && ((length + startIndex) > 0))
            {
                length += startIndex;
                startIndex = 0;
            }
            else
            {
                return "";
            }
            if ((str.Length - startIndex) < length)
            {
                length = str.Length - startIndex;
            }
            return str.Substring(startIndex, length);
        }

        public static void DebugWrite(string filepath, string message)
        {
            StreamWriter sr;
            if (System.IO.File.Exists(filepath))
            {
                sr = System.IO.File.AppendText(filepath);
            }
            else
            {
                sr = System.IO.File.CreateText(filepath);
            }
            sr.WriteLine("\n");
            sr.WriteLine(DateTime.Now.ToString() + "：" + message);
            sr.Close();
        }

        public static void DelCookie(string strName)
        {
            DelCookie(strName, "");
        }

        public static void DelCookie(string strName, Dictionary<string, string> dicKeyValues)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie != null)
            {
                if ((dicKeyValues != null) && (dicKeyValues.Count > 0))
                {
                    foreach (KeyValuePair<string, string> keyvalue in dicKeyValues)
                    {
                        if (keyvalue.Key != "")
                        {
                            cookie.Values.Remove(keyvalue.Key);
                        }
                    }
                }
                else
                {
                    cookie.Expires = DateTime.Now.Add(new TimeSpan(-1, 0, 0, 0));
                }
                HttpContext.Current.Response.AppendCookie(cookie);
            }
        }

        public static void DelCookie(string strName, string strKey)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie != null)
            {
                if (strKey != "")
                {
                    cookie.Values.Remove(strKey);
                }
                else
                {
                    cookie.Expires = DateTime.Now.Add(new TimeSpan(-1, 0, 0, 0));
                }
                HttpContext.Current.Response.AppendCookie(cookie);
            }
        }

        public static bool DeleteFile(string filePath)
        {
            try
            {
                System.IO.File.Delete(filePath);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static object Deserialize(string filepath, Type type)
        {
            XmlSerializer xs = new XmlSerializer(type);
            Stream stream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            object obj = xs.Deserialize(stream);
            stream.Close();
            return obj;
        }

        public static object DeserializeText(string txt, Type type)
        {
            string tmpstr = "<?xml version=\"1.0\" encoding=\"utf-16\"?>";
            object obj = null;
            txt = txt.Trim();
            if (txt.StartsWith(tmpstr) && (txt != tmpstr))
            {
                StringReader reader = new StringReader(txt);
                obj = new XmlSerializer(type).Deserialize(reader);
                reader.Close();
                reader.Dispose();
            }
            return obj;
        }

        public static string DeStr(string s)
        {
            StringBuilder sb = new StringBuilder();
            foreach (char c in s)
            {
                if (char.IsNumber(c))
                {
                    sb.Append(c);
                }
                else
                {
                    sb.Append('-');
                }
            }
            string[] ts = sb.ToString().Split(new char[] { '-' });
            int tCount = ts.Length;
            byte[] b = new byte[tCount];
            for (int i = 0; i < (tCount - 1); i++)
            {
                b[i] = byte.Parse(ts[i]);
            }
            return Encoding.Default.GetString(b);
        }

        public static string[] DistinctStringArray(string[] data)
        {
            if (data.Length > 0)
            {
                int i;
                Array.Sort<string>(data);
                int size = 1;
                for (i = 1; i < data.Length; i++)
                {
                    if (data[i] != data[i - 1])
                    {
                        size++;
                    }
                }
                string[] tempData = new string[size];
                int j = 0;
                tempData[j++] = data[0];
                for (i = 1; i < data.Length; i++)
                {
                    if (data[i] != data[i - 1])
                    {
                        tempData[j++] = data[i];
                    }
                }
                return tempData;
            }
            return data;
        }

        public static string EnStr(string s)
        {
            Random rnd = new Random();
            string z = "abfghk";
            byte[] b = Encoding.Default.GetBytes(s);
            StringBuilder sb = new StringBuilder();
            foreach (byte tb in b)
            {
                sb.Append(tb.ToString() + z[rnd.Next(0, 5)].ToString());
            }
            return sb.ToString();
        }

        public static string Escape(string str)
        {
            return GlobalObject.escape(str);
        }

        public static bool FileExists(string filename)
        {
            return System.IO.File.Exists(filename);
        }

        public static string[] FindNoUTF8File(string Path)
        {
            StringBuilder filelist = new StringBuilder();
            FileInfo[] subFiles = new DirectoryInfo(Path).GetFiles();
            for (int j = 0; j < subFiles.Length; j++)
            {
                if (subFiles[j].Extension.ToLower().Equals(".htm"))
                {
                    FileStream fs = new FileStream(subFiles[j].FullName, FileMode.Open, FileAccess.Read);
                    bool bUtf8 = IsUTF8(fs);
                    fs.Close();
                    if (!bUtf8)
                    {
                        filelist.Append(subFiles[j].FullName);
                        filelist.Append("\r\n");
                    }
                }
            }
            return SplitString(filelist.ToString(), "\r\n");
        }

        public static string FormatBytesStr(int bytes)
        {
            if (bytes > 1073741824)
            {
                return ((double)(bytes / 1073741824)).ToString("0") + "G";
            }
            if (bytes > 1048576)
            {
                return ((double)(bytes / 1048576)).ToString("0") + "M";
            }
            if (bytes > 1024)
            {
                return ((double)(bytes / 1024)).ToString("0") + "K";
            }
            return bytes.ToString() + "Bytes";
        }

        public static string GetAppPath()
        {
            string AppPath = HttpContext.Current.Request.ApplicationPath.Trim();
            if (AppPath.Length > 1)
            {
                AppPath = AppPath + "/";
            }
            return ("http://" + HttpContext.Current.Request.Url.Authority + AppPath);
        }

        public static string GetAssemblyCopyright()
        {
            return AssemblyFileVersion.LegalCopyright;
        }

        public static string GetAssemblyProductName()
        {
            return AssemblyFileVersion.ProductName;
        }

        public static string GetAssemblyVersion()
        {
            return string.Format("{0}.{1}.{2}", AssemblyFileVersion.FileMajorPart, AssemblyFileVersion.FileMinorPart, AssemblyFileVersion.FileBuildPart);
        }

        public static string GetCookie(string strName)
        {
            if ((HttpContext.Current.Request.Cookies != null) && (HttpContext.Current.Request.Cookies[strName] != null))
            {
                return HttpContext.Current.Request.Cookies[strName].Value.ToString();
            }
            return "";
        }

        public static string GetCookie(string strName, string strKey)
        {
            if (((HttpContext.Current.Request.Cookies != null) && (HttpContext.Current.Request.Cookies[strName] != null)) && (HttpContext.Current.Request.Cookies[strName][strKey] != null))
            {
                return HttpContext.Current.Request.Cookies[strName][strKey].ToString();
            }
            return "";
        }

        public static int GetCount(string strSource, string strArg)
        {
            return Regex.Matches(strSource, strArg).Count;
        }

        public static string GetDate()
        {
            return DateTime.Now.ToString("yyyy-MM-dd");
        }

        public static string GetDateTime()
        {
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        public static string GetDateTime(int relativeday)
        {
            return DateTime.Now.AddDays((double) relativeday).ToString("yyyy-MM-dd HH:mm:ss");
        }

        public static DateTime GetDateTime(string jsDateString)
        {
            return DateTime.ParseExact(jsDateString, "ddd MMM d HH:mm:ss 'UTC'zz'00' yyyy", CultureInfoDate);
        }

        public static string GetDateTimeCode()
        {
            return DateTime.Now.ToString("yyyyMMddHHmmssffff");
        }

        public static string GetFieldValue(Type tmptype, string fiename)
        {
            try
            {
                return tmptype.GetField(fiename, BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static).GetValue(null).ToString();
            }
            catch
            {
                return "";
            }
        }

        public static string[] GetFieldValues(Type tmptype)
        {
            string[] fieldstrings = null;
            try
            {
                FieldInfo[] fieldinfos = tmptype.GetFields(BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
                if (fieldinfos.Length <= 0)
                {
                    return fieldstrings;
                }
                int fcount = fieldinfos.Length;
                fieldstrings = new string[fcount];
                for (int i = 0; i < fcount; i++)
                {
                    fieldstrings[i] = fieldinfos[i].GetValue(null).ToString();
                }
            }
            catch
            {
            }
            return fieldstrings;
        }

        public static string GetFileExtName(string filename)
        {
            string[] array = filename.Trim().Split(new char[] { '.' });
            Array.Reverse(array);
            return array[0].ToString();
        }

        public static string GetFileName(string filename)
        {
            string[] str;
            if (IsNullOrEmpty(filename))
            {
                return "";
            }
            string reName = "";
            if (filename.IndexOf("/") >= 0)
            {
                str = filename.Split(new char[] { '/' });
                reName = str[str.Length - 1];
            }
            else if (filename.IndexOf(@"\") >= 0)
            {
                str = filename.Split(new char[] { '\\' });
                reName = str[str.Length - 1];
            }
            return reName;
        }

        public static string GetHref(string HtmlCode)
        {
            string MatchVale = "";
            string Reg = "(h|H)(r|R)(e|E)(f|F) *= *('|\")?((\\w|\\\\|\\/|\\.|:|-|_)+)[\\S]*";
            foreach (Match m in Regex.Matches(HtmlCode, Reg))
            {
                MatchVale = MatchVale + m.Value.ToLower().Replace("href=", "").Trim() + "|";
            }
            return MatchVale;
        }

        private static string GetImg(string ImgString)
        {
            string MatchVale = "";
            string Reg = @"src=.+\.(bmp|jpg|gif|png|)";
            foreach (Match m in Regex.Matches(ImgString.ToLower(), Reg))
            {
                MatchVale = MatchVale + m.Value.ToLower().Trim().Replace("src=", "").Trim(new char[] { '\'' }).Trim(new char[] { '"' });
            }
            return MatchVale;
        }

        public static string GetImgSrc(string HtmlCode)
        {
            string MatchVale = "";
            string Reg = "<img.+?>";
            foreach (Match m in Regex.Matches(HtmlCode.ToLower(), Reg))
            {
                MatchVale = MatchVale + GetImg(m.Value.ToLower().Trim()) + "|";
            }
            return MatchVale;
        }

        public static string GetJsDateTimeString()
        {
            return DateTime.Now.ToString("ddd MMM d HH:mm:ss 'UTC'zz'00' yyyy", CultureInfoDate);
        }

        public static string GetMapPath(string strPath)
        {
            if (HttpContext.Current != null)
            {
                return HttpContext.Current.Server.MapPath(strPath);
            }
            strPath = strPath.Replace("/", @"\");
            if (strPath.StartsWith(@"\"))
            {
                strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart(new char[] { '\\' });
            }
            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
        }

        public static string GetMapSrc(string oldSrc, string httpUrl)
        {
            oldSrc = oldSrc.Trim().ToLower();
            httpUrl = httpUrl.Trim().ToLower();
            string http = "http://";
            int tFlag = httpUrl.LastIndexOf('/');
            if (tFlag > 0)
            {
                httpUrl = httpUrl.Substring(0, tFlag);
            }
            if (oldSrc.StartsWith(http))
            {
                return oldSrc;
            }
            if (oldSrc.StartsWith("/"))
            {
                if (httpUrl.StartsWith(http))
                {
                    httpUrl = httpUrl.Replace(http, "");
                }
                int iFlag = httpUrl.IndexOf('/');
                if (iFlag > 0)
                {
                    httpUrl = httpUrl.Substring(0, iFlag);
                }
                return (http + httpUrl + oldSrc);
            }
            if (oldSrc.StartsWith("./"))
            {
                return (httpUrl + oldSrc.Trim(new char[] { '.' }));
            }
            while (oldSrc.StartsWith(".."))
            {
                oldSrc = oldSrc.Trim(new char[] { '.' }).Trim(new char[] { '/' });
                int tCount = httpUrl.LastIndexOf('/');
                if (tCount > 0)
                {
                    httpUrl = httpUrl.Substring(0, tCount);
                }
            }
            return (httpUrl + "/" + oldSrc);
        }

        public static double GetMemorySize()
        {
            return (((double) Process.GetCurrentProcess().WorkingSet64) / 1048576.0);
        }

        public static string GetMinDate()
        {
            return "1900-01-01";
        }

        public static string GetParam(string strHref, string strName)
        {
            int intPos = strHref.IndexOf("?");
            if (intPos >= 0)
            {
                string[] arrPram = SplitString(strHref.Substring(intPos + 1), "&");
                for (int i = 0; i < arrPram.Length; i++)
                {
                    string[] arrPramName = SplitString(arrPram[i], "=");
                    if (arrPramName[0].ToLower() == strName.ToLower())
                    {
                        return arrPramName[1];
                    }
                }
            }
            return "";
        }

        private static string GetPinYinChar(string c)
        {
            byte[] array = new byte[2];
            array = Encoding.Default.GetBytes(c);
            int i = (array[0] * 0x100) + array[1];
            if (i >= 0xb0a1)
            {
                if (i < 0xb0c5)
                {
                    return "a";
                }
                if (i < 0xb2c1)
                {
                    return "b";
                }
                if (i < 0xb4ee)
                {
                    return "c";
                }
                if (i < 0xb6ea)
                {
                    return "d";
                }
                if (i < 0xb7a2)
                {
                    return "e";
                }
                if (i < 0xb8c1)
                {
                    return "f";
                }
                if (i < 0xb9fe)
                {
                    return "g";
                }
                if (i < 0xbbf7)
                {
                    return "h";
                }
                if (i < 0xbfa6)
                {
                    return "g";
                }
                if (i < 0xc0ac)
                {
                    return "k";
                }
                if (i < 0xc2e8)
                {
                    return "l";
                }
                if (i < 0xc4c3)
                {
                    return "m";
                }
                if (i < 0xc5b6)
                {
                    return "n";
                }
                if (i < 0xc5be)
                {
                    return "o";
                }
                if (i < 0xc6da)
                {
                    return "p";
                }
                if (i < 0xc8bb)
                {
                    return "q";
                }
                if (i < 0xc8f6)
                {
                    return "r";
                }
                if (i < 0xcbfa)
                {
                    return "s";
                }
                if (i < 0xcdda)
                {
                    return "t";
                }
                if (i < 0xcef4)
                {
                    return "w";
                }
                if (i < 0xd1b9)
                {
                    return "x";
                }
                if (i < 0xd4d1)
                {
                    return "y";
                }
                if (i < 0xd7fa)
                {
                    return "z";
                }
            }
            return "*";
        }

        public static string GetPinYinString(string str)
        {
            string tempStr = "";
            foreach (char c in str)
            {
                if ((c >= '!') && (c <= '~'))
                {
                    tempStr = tempStr + c.ToString();
                }
                else
                {
                    tempStr = tempStr + GetPinYinChar(c.ToString());
                }
            }
            return tempStr;
        }

        public static string GetPropertyValue(Type tmptype, string proname)
        {
            try
            {
                return tmptype.GetProperty(proname, BindingFlags.GetProperty | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static).GetValue(null, null).ToString();
            }
            catch
            {
                return "";
            }
        }

        public static string[] GetPropertyValues(Type tmptype)
        {
            string[] prostrings = null;
            try
            {
                PropertyInfo[] proinfos = tmptype.GetProperties(BindingFlags.GetProperty | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
                if (proinfos.Length <= 0)
                {
                    return prostrings;
                }
                int fcount = proinfos.Length;
                prostrings = new string[fcount];
                for (int i = 0; i < fcount; i++)
                {
                    prostrings[i] = proinfos[i].GetValue(null, null).ToString();
                }
            }
            catch
            {
            }
            return prostrings;
        }

        public static string GetRealIP()
        {
            string ip = "";
            try
            {
                HttpRequest request = HttpContext.Current.Request;
                if (request.ServerVariables["HTTP_VIA"] != null)
                {
                    return request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(new char[] { ',' })[0].Trim();
                }
                ip = request.UserHostAddress;
            }
            catch
            {
            }
            return ip;
        }

        public static RegexOptions GetRegexCompiledOptions()
        {
            return RegexOptions.None;
        }

        public static string GetSpacesString(int spacesCount)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < spacesCount; i++)
            {
                sb.Append(" &nbsp;&nbsp;");
            }
            return sb.ToString();
        }

        public static string GetStandardDateTime()
        {
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fffffff");
        }

        public static int GetStringLength(string str)
        {
            return Encoding.Default.GetBytes(str).Length;
        }

        public static string GetSubString(string Str, int Num)
        {
            if (IsNullOrEmpty(Str))
            {
                return "";
            }
            string outstr = "";
            int n = 0;
            foreach (char ch in Str)
            {
                n += Encoding.Default.GetByteCount(ch.ToString());
                if (n > Num)
                {
                    return outstr;
                }
                outstr = outstr + ch;
            }
            return outstr;
        }

        public static string GetSubString(string Str, int Num, string LastStr)
        {
            return ((Str.Length > Num) ? (Str.Substring(0, Num) + LastStr) : Str);
        }

        public static string GetTextByUrl(string url)
        {
            WebRequest request = WebRequest.Create(url);
            request.Timeout = 0x4e20;
            StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream());
            return sr.ReadToEnd();
        }

        public static string GetTextFromHtml(string HTML)
        {
            Regex regEx = new Regex("</?(?!br|/?p|img)[^>]*>", RegexOptions.IgnoreCase);
            return regEx.Replace(HTML, "");
        }

        public static string GetTime()
        {
            return DateTime.Now.ToString("HH:mm:ss");
        }

        public static string GetUrlFileName(string url)
        {
            if (IsNullOrEmpty(url))
            {
                return "";
            }
            string[] strs1 = url.Split(new char[] { '/' });
            return strs1[strs1.Length - 1].Split(new char[] { '?' })[0];
        }

        public static string GetViaIP()
        {
            string ip = "";
            try
            {
                HttpRequest request = HttpContext.Current.Request;
                if (request.ServerVariables["HTTP_VIA"] != null)
                {
                    ip = request.UserHostAddress;
                }
            }
            catch
            {
            }
            return ip;
        }

        public static string Help()
        {
            return "mailto:354990393@qq.com";
        }

        public static string HtmlDecode(string str)
        {
            return HttpUtility.HtmlDecode(str);
        }

        public static string HtmlEncode(string str)
        {
            return HttpUtility.HtmlEncode(str);
        }

        public static bool InIPArray(string ip, string[] iparray)
        {
            string[] userip = SplitString(ip, ".");
            for (int ipIndex = 0; ipIndex < iparray.Length; ipIndex++)
            {
                string[] tmpip = SplitString(iparray[ipIndex], ".");
                int r = 0;
                for (int i = 0; i < tmpip.Length; i++)
                {
                    if (tmpip[i] == "*")
                    {
                        return true;
                    }
                    if ((userip.Length > i) && (tmpip[i] == userip[i]))
                    {
                        r++;
                    }
                    else
                    {
                        break;
                    }
                }
                if (r == 4)
                {
                    return true;
                }
            }
            return false;
        }

        public static bool IsBase64String(string str)
        {
            return Regex.IsMatch(str, @"[A-Za-z0-9\+\/\=]");
        }

        public static bool IsDateString(string str)
        {
            return Regex.IsMatch(str, @"(\d{4})-(\d{1,2})-(\d{1,2})");
        }

        public static bool IsDouble(string expression)
        {
            return (!IsNullOrEmpty(expression) && Regex.IsMatch(expression, @"^([0-9])[0-9]*(\.\w*)?$"));
        }

        public static bool IsImgFileName(string filename)
        {
            filename = filename.Trim();
            if (filename.EndsWith(".") || (filename.IndexOf(".") == -1))
            {
                return false;
            }
            string extname = filename.Substring(filename.LastIndexOf(".") + 1).ToLower();
            return ((((extname == "jpg") || (extname == "jpeg")) || ((extname == "png") || (extname == "bmp"))) || (extname == "gif"));
        }

        public static bool IsIP(string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }

        public static bool IsIPSect(string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){2}((2[0-4]\d|25[0-5]|[01]?\d\d?|\*)\.)(2[0-4]\d|25[0-5]|[01]?\d\d?|\*)$");
        }

        public static bool IsNullOrEmpty(string str)
        {
            return ((str == null) || (str.Trim() == ""));
        }

        public static bool IsNumeric(string expression)
        {
            if (!IsNullOrEmpty(expression))
            {
                string str = expression;
                if ((((str.Length > 0) && (str.Length <= 11)) && Regex.IsMatch(str, "^[-]?[0-9]*[.]?[0-9]*$")) && (((str.Length < 10) || ((str.Length == 10) && (str[0] == '1'))) || (((str.Length == 11) && (str[0] == '-')) && (str[1] == '1'))))
                {
                    return true;
                }
            }
            return false;
        }

        public static bool IsNumericArray(string[] strNumber)
        {
            if (strNumber == null)
            {
                return false;
            }
            if (strNumber.Length < 1)
            {
                return false;
            }
            foreach (string id in strNumber)
            {
                if (!IsNumeric(id))
                {
                    return false;
                }
            }
            return true;
        }

        public static bool IsNumericList(string numList)
        {
            if (numList == "")
            {
                return false;
            }
            foreach (string num in numList.Split(new char[] { ',' }))
            {
                if (!IsNumeric(num))
                {
                    return false;
                }
            }
            return true;
        }

        public static bool IsSafeLinkString(string str)
        {
            return !Regex.IsMatch(str, "^\\s*$|^c:\\\\con\\\\con$|[%,\\*\"\\s\\t\\<\\>\\&]|游客|^Guest");
        }

        public static bool IsSafeSqlString(string str)
        {
            return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
        }

        public static bool IsTime(string timeval)
        {
            return Regex.IsMatch(timeval, "^((([0-1]?[0-9])|(2[0-3])):([0-5]?[0-9])(:[0-5]?[0-9])?)$");
        }

        public static bool IsUrl(string strUrl)
        {
            return Regex.IsMatch(strUrl, @"^(http|https)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{1,10}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$");
        }

        private static bool IsUTF8(FileStream sbInputStream)
        {
            bool bAllAscii = true;
            long iLen = sbInputStream.Length;
            byte cOctets = 0;
            for (int i = 0; i < iLen; i++)
            {
                byte chr = (byte) sbInputStream.ReadByte();
                if ((chr & 0x80) != 0)
                {
                    bAllAscii = false;
                }
                if (cOctets == 0)
                {
                    if (chr >= 0x80)
                    {
                        do
                        {
                            chr = (byte) (chr << 1);
                            cOctets = (byte) (cOctets + 1);
                        }
                        while ((chr & 0x80) != 0);
                        cOctets = (byte) (cOctets - 1);
                        if (cOctets == 0)
                        {
                            return false;
                        }
                    }
                }
                else
                {
                    if ((chr & 0xc0) != 0x80)
                    {
                        return false;
                    }
                    cOctets = (byte) (cOctets - 1);
                }
            }
            if (cOctets > 0)
            {
                return false;
            }
            if (bAllAscii)
            {
                return false;
            }
            return true;
        }

        public static bool IsValidEmail(string strEmail)
        {
            return Regex.IsMatch(strEmail, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }

        public static int LongToInt(object objNum)
        {
            if (objNum != null)
            {
                string strNum = objNum.ToString();
                if (IsNumeric(strNum))
                {
                    if (strNum.ToString().Length > 9)
                    {
                        if (strNum.StartsWith("-"))
                        {
                            return -2147483648;
                        }
                        return 0x7fffffff;
                    }
                    return int.Parse(strNum);
                }
            }
            return 0;
        }

        [DllImport("dbgHelp", SetLastError=true)]
        private static extern bool MakeSureDirectoryPathExists(string name);
        public static string ReadFile(string path)
        {
            return ReadFile(path, Encoding.Default);
        }

        public static string ReadFile(string path, int tCount)
        {
            return ReadFile(path, tCount, Encoding.Default);
        }

        public static string ReadFile(string path, Encoding encode)
        {
            StringBuilder html = new StringBuilder();
            try
            {
                using (StreamReader reader = new StreamReader(path, encode))
                {
                    while (reader.Peek() >= 0)
                    {
                        html.Append(((char) reader.Read()).ToString());
                    }
                }
            }
            catch
            {
                return null;
            }
            return html.ToString();
        }

        public static string ReadFile(string path, int tCount, Encoding encode)
        {
            Encoding code = encode;
            StreamReader sr = null;
            StringBuilder sb = new StringBuilder();
            string temppath = path;
            try
            {
                sr = new StreamReader(temppath, code);
                sb.Append("<pre>");
                while (sr.Peek() >= 0)
                {
                    string strMbContect = sr.ReadLine();
                    if (strMbContect.Length > tCount)
                    {
                        strMbContect = strMbContect.Remove(0, tCount);
                    }
                    else
                    {
                        strMbContect = "";
                    }
                    sb.Append("<br>" + strMbContect);
                }
                sb.Append("</pre>");
            }
            catch
            {
                if (sr != null)
                {
                    sr.Close();
                }
                sb.Remove(0, sb.Length);
            }
            return sb.ToString();
        }

        public static string ReadFileToEnd(string path)
        {
            return ReadFileToEnd(path, Encoding.Default);
        }

        public static string ReadFileToEnd(string path, Encoding encode)
        {
            try
            {
                StreamReader reader = new StreamReader(path, encode);
                string str = reader.ReadToEnd();
                reader.Close();
                return str;
            }
            catch
            {
                return null;
            }
        }

        public static string RemoveHtml(string content)
        {
            string regexstr = "<[^>]*>";
            return Regex.Replace(content, regexstr, string.Empty, RegexOptions.IgnoreCase);
        }

        public static string RemoveUnsafeHtml(string content)
        {
            content = Regex.Replace(content, @"(\<|\s+)o([a-z]+\s?=)", "$1$2", RegexOptions.IgnoreCase);
            content = Regex.Replace(content, @"(script|frame|form|meta|behavior|style)([\s|:|>])+", "$1.$2", RegexOptions.IgnoreCase);
            return content;
        }

        public static string ReplaceStrToScript(string str)
        {
            str = str.Replace(@"\", @"\\");
            str = str.Replace("'", @"\'");
            str = str.Replace("\"", "\\\"");
            return str;
        }

        public static void ResponseFile(string filepath, string filename, string filetype)
        {
            Stream iStream = null;
            byte[] buffer = new byte[0x2710];
            try
            {
                iStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                long dataToRead = iStream.Length;
                HttpContext.Current.Response.ContentType = filetype;
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + UrlEncode(filename.Trim()).Replace("+", " "));
                while (dataToRead > 0)
                {
                    if (HttpContext.Current.Response.IsClientConnected)
                    {
                        int length = iStream.Read(buffer, 0, 0x2710);
                        HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
                        HttpContext.Current.Response.Flush();
                        buffer = new byte[0x2710];
                        dataToRead -= length;
                    }
                    else
                    {
                        dataToRead = -1;
                    }
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("Error : " + ex.Message);
            }
            finally
            {
                if (iStream != null)
                {
                    iStream.Close();
                }
            }
            HttpContext.Current.Response.End();
        }

        public static bool RestoreFile(string backupFileName, string targetFileName)
        {
            return RestoreFile(backupFileName, targetFileName, null);
        }

        public static bool RestoreFile(string backupFileName, string targetFileName, string backupTargetFileName)
        {
            try
            {
                if (!System.IO.File.Exists(backupFileName))
                {
                    throw new FileNotFoundException(backupFileName + "文件不存在！");
                }
                if (backupTargetFileName != null)
                {
                    if (!System.IO.File.Exists(targetFileName))
                    {
                        throw new FileNotFoundException(targetFileName + "文件不存在！无法备份此文件！");
                    }
                    System.IO.File.Copy(targetFileName, backupTargetFileName, true);
                }
                System.IO.File.Delete(targetFileName);
                System.IO.File.Copy(backupFileName, targetFileName);
            }
            catch (Exception e)
            {
                throw e;
            }
            return true;
        }

        public static string SBCCaseToNumberic(string SBCCase)
        {
            char[] c = SBCCase.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                byte[] b = Encoding.Unicode.GetBytes(c, i, 1);
                if ((b.Length == 2) && (b[1] == 0xff))
                {
                    b[0] = (byte) (b[0] + 0x20);
                    b[1] = 0;
                    c[i] = Encoding.Unicode.GetChars(b)[0];
                }
            }
            return new string(c);
        }

        public static void Serialiaze(string filepath, object obj, Type type)
        {
            XmlSerializer xs = new XmlSerializer(type);
            Stream stream = new FileStream(filepath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
            xs.Serialize(stream, obj);
            stream.Close();
        }

        public static string SerialiazeText(object obj, Type type)
        {
            StringWriter writer = new StringWriter();
            new XmlSerializer(type).Serialize((TextWriter) writer, obj);
            StringBuilder sb = writer.GetStringBuilder();
            writer.Close();
            writer.Dispose();
            return sb.ToString();
        }

        public static void SetCookie(string strName, string strValue)
        {
            SetCookie(strName, "", strValue, 0);
        }

        public static void SetCookie(string strName, Dictionary<string, string> dicKeyValues, int expires)
        {
            if ((dicKeyValues != null) && (dicKeyValues.Count > 0))
            {
                HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
                if (cookie == null)
                {
                    cookie = new HttpCookie(strName);
                }
                foreach (KeyValuePair<string, string> keyvalue in dicKeyValues)
                {
                    if ((cookie.Values[keyvalue.Key] == null) || (cookie.Values[keyvalue.Key].Trim() == ""))
                    {
                        cookie.Values.Add(keyvalue.Key, keyvalue.Value);
                    }
                    else
                    {
                        cookie.Values.Set(keyvalue.Key, keyvalue.Value);
                    }
                }
                if (expires > 0)
                {
                    cookie.Expires = DateTime.Now.AddMinutes((double) expires);
                }
                HttpContext.Current.Response.AppendCookie(cookie);
            }
        }

        public static void SetCookie(string strName, string strValue, int expires)
        {
            SetCookie(strName, "", strValue, expires);
        }

        public static void SetCookie(string strName, string strKey, string strValue)
        {
            SetCookie(strName, strKey, strValue, 0);
        }

        public static void SetCookie(string strName, string strKey, string strValue, int expires)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie == null)
            {
                cookie = new HttpCookie(strName);
            }
            if (strKey == "")
            {
                cookie.Value = strValue;
            }
            else if ((cookie.Values[strKey] == null) || (cookie.Values[strKey].Trim() == ""))
            {
                cookie.Values.Add(strKey, strValue);
            }
            else
            {
                cookie.Values.Set(strKey, strValue);
            }
            if (expires > 0)
            {
                cookie.Expires = DateTime.Now.AddMinutes((double) expires);
            }
            HttpContext.Current.Response.AppendCookie(cookie);
        }

        public static string[] SplitString(string strContent, string strSplit)
        {
            if (!IsNullOrEmpty(strContent))
            {
                if (strContent.IndexOf(strSplit) < 0)
                {
                    return new string[] { strContent };
                }
                return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase);
            }
            return new string[0];
        }

        public static int StrDateDiffHours(string time, int hours)
        {
            if ((time == "") || (time == null))
            {
                return 1;
            }
            TimeSpan ts = (TimeSpan) (DateTime.Now - DateTime.Parse(time).AddHours((double) hours));
            if (ts.TotalHours > 2147483647.0)
            {
                return 0x7fffffff;
            }
            if (ts.TotalHours < -2147483648.0)
            {
                return -2147483648;
            }
            return (int) ts.TotalHours;
        }

        public static int StrDateDiffMinutes(string time, int minutes)
        {
            if ((time == "") || (time == null))
            {
                return 1;
            }
            TimeSpan ts = (TimeSpan) (DateTime.Now - DateTime.Parse(time).AddMinutes((double) minutes));
            if (ts.TotalMinutes > 2147483647.0)
            {
                return 0x7fffffff;
            }
            if (ts.TotalMinutes < -2147483648.0)
            {
                return -2147483648;
            }
            return (int) ts.TotalMinutes;
        }

        public static int StrDateDiffSeconds(string Time, int Sec)
        {
            TimeSpan ts = (TimeSpan) (DateTime.Now - DateTime.Parse(Time).AddSeconds((double) Sec));
            if (ts.TotalSeconds > 2147483647.0)
            {
                return 0x7fffffff;
            }
            if (ts.TotalSeconds < -2147483648.0)
            {
                return -2147483648;
            }
            return (int) ts.TotalSeconds;
        }

        public static string StringOfChar(int strLong, string str)
        {
            string ReturnStr = "";
            for (int i = 0; i < strLong; i++)
            {
                ReturnStr = ReturnStr + str;
            }
            return ReturnStr;
        }

        public static bool StrToBool(object expression, bool defValue)
        {
            if (expression != null)
            {
                return StrToBool(expression, defValue);
            }
            return defValue;
        }

        public static bool StrToBool(string expression, bool defValue)
        {
            if (expression != null)
            {
                if (string.Compare(expression, "true", true) == 0)
                {
                    return true;
                }
                if (string.Compare(expression, "false", true) == 0)
                {
                    return false;
                }
            }
            return defValue;
        }

        public static float StrToFloat(object strValue, float defValue)
        {
            if (strValue == null)
            {
                return defValue;
            }
            return StrToFloat(strValue.ToString(), defValue);
        }

        public static float StrToFloat(string strValue, float defValue)
        {
            if ((strValue == null) || (strValue.Length > 10))
            {
                return defValue;
            }
            float intValue = defValue;
            if ((strValue != null) && Regex.IsMatch(strValue, @"^([-]|[0-9])[0-9]*(\.\w*)?$"))
            {
                intValue = System.Convert.ToSingle(strValue);
            }
            return intValue;
        }

        public static string StrToHtmlNewLines(string str)
        {
            if (str == null)
            {
                return "";
            }
            str = str.Replace("\r\n", "<br />");
            str = str.Replace("\n", "<br />");
            return str;
        }

        public static int StrToInt(object expression, int defValue)
        {
            if (expression != null)
            {
                return StrToInt(expression.ToString(), defValue);
            }
            return defValue;
        }

        public static int StrToInt(string str, int defValue)
        {
            if ((str != null) && ((((str.Length > 0) && (str.Length <= 11)) && Regex.IsMatch(str, "^[-]?[0-9]*$")) && (((str.Length < 10) || ((str.Length == 10) && (str[0] == '1'))) || (((str.Length == 11) && (str[0] == '-')) && (str[1] == '1')))))
            {
                return System.Convert.ToInt32(str);
            }
            return defValue;
        }

        public static Color ToColor(string color)
        {
            int red;
            int green;
            char[] rgb;
            int blue = 0;
            color = color.TrimStart(new char[] { '#' });
            color = Regex.Replace(color.ToLower(), "[g-zG-Z]", "");
            switch (color.Length)
            {
                case 3:
                    rgb = color.ToCharArray();
                    red = System.Convert.ToInt32(rgb[0].ToString() + rgb[0].ToString(), 0x10);
                    green = System.Convert.ToInt32(rgb[1].ToString() + rgb[1].ToString(), 0x10);
                    blue = System.Convert.ToInt32(rgb[2].ToString() + rgb[2].ToString(), 0x10);
                    return Color.FromArgb(red, green, blue);

                case 6:
                    rgb = color.ToCharArray();
                    red = System.Convert.ToInt32(rgb[0].ToString() + rgb[1].ToString(), 0x10);
                    green = System.Convert.ToInt32(rgb[2].ToString() + rgb[3].ToString(), 0x10);
                    blue = System.Convert.ToInt32(rgb[4].ToString() + rgb[5].ToString(), 0x10);
                    return Color.FromArgb(red, green, blue);
            }
            return Color.FromName(color);
        }

        public static string ToSChinese(string str)
        {
            return Strings.StrConv(str, VbStrConv.SimplifiedChinese, 0);
        }

        public static string ToTChinese(string str)
        {
            return Strings.StrConv(str, VbStrConv.TraditionalChinese, 0);
        }

        public void TransHtml(string path, string outpath)
        {
            FileStream fs;
            Page page = new Page();
            StringWriter writer = new StringWriter();
            page.Server.Execute(path, writer);
            if (System.IO.File.Exists(page.Server.MapPath("") + @"\" + outpath))
            {
                System.IO.File.Delete(page.Server.MapPath("") + @"\" + outpath);
                fs = System.IO.File.Create(page.Server.MapPath("") + @"\" + outpath);
            }
            else
            {
                fs = System.IO.File.Create(page.Server.MapPath("") + @"\" + outpath);
            }
            byte[] bt = Encoding.Default.GetBytes(writer.ToString());
            fs.Write(bt, 0, bt.Length);
            fs.Close();
        }

        public static string UnEscape(string str)
        {
            return GlobalObject.unescape(str);
        }

        public static string UrlDecode(string str)
        {
            return HttpUtility.UrlDecode(str);
        }

        public static string UrlEncode(string str)
        {
            return HttpUtility.UrlEncode(str);
        }

        public static string ZipHtml(string Html)
        {
            Html = Regex.Replace(Html, @">\s+?<", "><");
            Html = Regex.Replace(Html, @"\r\n\s*", "");
            Html = Regex.Replace(Html, @"<body([\s|\S]*?)>([\s|\S]*?)</body>", "<body$1>$2</body>", RegexOptions.IgnoreCase);
            return Html;
        }

        public static string[] Monthes
        {
            get
            {
                return new string[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
            }
        }
    }
}

